<!--
 - 用户区域授权详情页面
 - 显示用户信息和管辖区域树
 - 支持编辑用户管辖区域
-->
<script setup lang="ts">
import { nextTick } from "vue";
import {
  ElTree,
  ElButton,
  ElCard,
  ElDescriptions,
  ElDescriptionsItem,
  ElMessage,
  ElInput,
  ElIcon,
  ElRadioGroup,
  ElRadioButton,
} from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  getUserAreaTree,
  editUserArea,
} from "@/plugins/ai-warning/organization/api/rdOrganizeUserStand.ts";
import { ResultCode } from "@/utils/ResultCode.ts";

defineOptions({ name: "organization:rdOrganizeUser:detail" });

const props = defineProps<{
  userData: any;
}>();

const t = useTrans().globalTrans;
const treeRef = ref();
const loading = ref(false);
const treeData = ref<any[]>([]);
const filterText = ref<string>("");
const isExpand = ref<boolean>(true);

// 树配置
const defaultProps = {
  children: "children",
  label: "name",
};

// 生成唯一的节点键（因为不同层级的ID会重复）
const generateNodeKey = (
  node: any,
  level: string,
  parentKey?: string
): string => {
  if (parentKey) {
    return `${parentKey}-${level}-${node.id}`;
  }
  return `${level}-${node.id}`;
};

// 为树数据添加唯一的nodeKey
const addNodeKeys = (
  nodes: any[],
  level: string,
  parentKey?: string
): any[] => {
  return nodes.map((node) => {
    const nodeKey = generateNodeKey(node, level, parentKey);
    const newNode = {
      ...node,
      nodeKey,
      originalId: node.id, // 保存原始ID，用于提交数据
      role: node.role || 1, // 保存角色信息，默认为管理员
    };

    if (node.children && node.children.length > 0) {
      // 根据当前层级确定下一层级
      let nextLevel = level;
      if (level === "zone") nextLevel = "work";
      else if (level === "work") nextLevel = "project";
      else if (level === "project") nextLevel = "stand";

      newNode.children = addNodeKeys(node.children, nextLevel, nodeKey);
    }

    return newNode;
  });
};

// 加载用户区域树数据
const loadTreeData = async () => {
  loading.value = true;
  try {
    const response = await getUserAreaTree(props.userData.user_id);
    if (response.code === ResultCode.SUCCESS) {
      // 过滤掉没有站点的分支
      const filteredData = filterTreeData(response.data);
      // 为所有节点添加唯一的nodeKey
      const dataWithKeys = addNodeKeys(filteredData, "zone");
      treeData.value = dataWithKeys;

      // 设置初始选中的站点
      await nextTick();
      const checkedStands = getAllStandNodes(dataWithKeys).filter(
        (node) => node.checked
      );
      const checkedKeys = checkedStands.map((node) => node.nodeKey);
      treeRef.value?.setCheckedKeys(checkedKeys);
    }
  } catch (error) {
    console.error("加载区域树数据失败:", error);
    ElMessage.error("加载区域树数据失败");
  } finally {
    loading.value = false;
  }
};

// 过滤树数据，只保留有站点的分支
const filterTreeData = (data: any[]): any[] => {
  return data.filter((node: any) => {
    if (node.children && node.children.length > 0) {
      // 递归过滤子节点
      node.children = filterTreeData(node.children);
      // 如果过滤后还有子节点，保留该节点
      return node.children.length > 0;
    }
    // 如果有checked字段，说明是站点，保留该节点
    return node.hasOwnProperty("checked");
  });
};

// 检查节点是否为站点（最底层）
const isStandNode = (node: any): boolean => {
  return node.hasOwnProperty("checked");
};

// 获取所有站点节点
const getAllStandNodes = (nodes: any[]): any[] => {
  const stands: any[] = [];
  const traverse = (nodeList: any[]) => {
    nodeList.forEach((node: any) => {
      if (isStandNode(node)) {
        stands.push(node);
      }
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    });
  };
  traverse(nodes);
  return stands;
};

// 保存用户区域
const saveUserArea = async () => {
  loading.value = true;
  try {
    // 获取所有选中的站点节点
    const checkedNodes = treeRef.value?.getCheckedNodes(false, true) || [];
    
    // 获取选中的站点ID集合，用于判断每个站点是否被选中
    const checkedStandIds = new Set(
      checkedNodes
        .filter((node: any) => isStandNode(node))
        .map((node: any) => node.originalId)
    );

    // 获取所有站点节点（包括选中和未选中的）
    const allStandNodes = getAllStandNodes(treeData.value);

    // 构建提交数据，包含所有站点信息
    const submitData = {
      user_id: props.userData.user_id,
      data: allStandNodes.map((node: any) => ({
        stand_id: node.originalId, // 站点ID
        role: checkedStandIds.has(node.originalId) ? (node.role || 1) : 1, // 选中的使用实际角色，未选中的默认1
        status: checkedStandIds.has(node.originalId) ? 1 : 2, // 1表示选中，2表示未选中
      })),
    };

    const response = await editUserArea(submitData);

    if (response.code === ResultCode.SUCCESS) {
      ElMessage.success("保存成功");
      // 重新加载数据
      await loadTreeData();
    } else {
      ElMessage.error(response.message || "保存失败");
    }
  } catch (error) {
    console.error("保存用户区域失败:", error);
    ElMessage.error("保存失败");
  } finally {
    loading.value = false;
  }
};

// 搜索过滤方法
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name?.includes(value);
};

// 监听搜索框变化
watch(filterText, (val) => {
  treeRef.value?.filter(val);
});

// 切换展开/折叠
const toggleExpand = () => {
  isExpand.value = !isExpand.value;
  const nodes = treeRef.value?.store?._getAllNodes();
  nodes?.forEach((node: any) => {
    node.expanded = isExpand.value;
  });
};

// 切换站点角色
const handleRoleChange = (node: any, role: number) => {
  node.role = role;
};

// 角色选项
const roleOptions = [
  { label: "管理员", value: 1 },
  { label: "安全员", value: 2 },
];

// 页面加载时获取数据
onMounted(() => {
  loadTreeData();
});

// 暴露保存方法给父组件调用
defineExpose({
  saveUserArea,
});
</script>

<template>
  <div class="user-area-detail" v-loading="loading">
    <!-- 用户管辖区域树 -->
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-lg font-semibold">
            {{ userData.user?.username || "用户" }} 的区域授权
          </span>
        </div>
      </template>

      <div class="tree-container">
        <!-- 搜索和操作栏 -->
        <div class="tree-toolbar">
          <el-input
            v-model="filterText"
            placeholder="搜索区域名称"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button @click="toggleExpand">
            {{ isExpand ? "折叠" : "展开" }}
          </el-button>
        </div>

        <!-- 树结构 -->
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="defaultProps"
          node-key="nodeKey"
          :show-checkbox="true"
          :check-strictly="false"
          :default-expand-all="true"
          :filter-node-method="filterNode"
          class="tree-content"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span class="node-label">{{ data.name }}</span>
              <!-- 只在站点节点被选中时显示角色选择器 -->
              <el-radio-group
                v-if="data.hasOwnProperty('checked') && node.checked"
                v-model="data.role"
                size="small"
                @change="handleRoleChange(data, data.role)"
                @click.stop
                class="role-selector"
              >
                <el-radio-button
                  v-for="option in roleOptions"
                  :key="option.value"
                  :label="option.value"
                >
                  {{ option.label }}
                </el-radio-button>
              </el-radio-group>
            </div>
          </template>
        </el-tree>

        <!-- 空状态 -->
        <div v-if="!treeData || treeData.length === 0" class="empty-state">
          <el-empty description="暂无管辖区域数据" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.user-area-detail {
  padding: 20px;

  .tree-container {
    .tree-toolbar {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 16px;
      padding: 12px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .search-input {
        flex: 1;
      }
    }

    .tree-content {
      min-height: 400px;
      max-height: 500px;
      overflow-y: auto;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 8px;
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      gap: 12px;

      .node-label {
        flex: 1;
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .role-selector {
        flex-shrink: 0;
        margin-left: auto;
      }
    }

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 400px;
    }
  }
}

:deep(.el-tree-node__content) {
  height: 36px;
}

:deep(.el-tree-node__label) {
  font-size: 14px;
}
</style>
